import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/Home.vue'),
      meta: { title: '首页' }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register.vue'),
      meta: { title: '注册' }
    },
    {
      path: '/talk',
      name: 'talk',
      component: () => import('@/views/Talk.vue'),
      meta: { title: '说说', requiresAuth: true }
    },
    {
      path: '/talk/publish',
      name: 'talkPublish',
      component: () => import('@/views/TalkPublish.vue'),
      meta: { title: '发布说说', requiresAuth: true }
    },
    {
      path: '/talk/edit/:id',
      name: 'talkEdit',
      component: () => import('@/views/TalkPublish.vue'),
      meta: { title: '编辑说说', requiresAuth: true }
    },
    {
      path: '/article',
      name: 'article',
      component: () => import('@/views/Article.vue'),
      meta: { title: '文章' }
    },
    {
      path: '/album',
      name: 'album',
      component: () => import('@/views/Album.vue'),
      meta: { title: '相册' }
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('@/views/Profile.vue'),
      meta: { title: '个人中心', requiresAuth: true }
    },
    {
      path: '/settings',
      name: 'settings',
      component: () => import('@/views/Settings.vue'),
      meta: { title: '设置', requiresAuth: true }
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('@/views/Test.vue'),
      meta: { title: '功能测试' }
    },
    {
      path: '/video-test',
      name: 'videoTest',
      component: () => import('@/views/test/VideoTest.vue'),
      meta: { title: '视频播放测试' }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 我的博客` : '我的博客'

  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLoggedIn()) {
    next('/login')
  } else {
    next()
  }
})

export default router
